package com.plc.demo.controller;

import com.plc.demo.service.PlcDataService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * PLC数据控制器
 */
@RestController
@RequestMapping("/api/plc")
public class PlcController {

    @Autowired
    private PlcDataService plcDataService;

    /**
     * 下发数据读取请求
     *
     * @param devId       设备ID
     * @param addressType 地址类型，如 "VW"
     * @param startValue  起始值
     * @param endValue    终止值
     * @param increment   增量
     * @param targetValue 目标值（用于标记接近的值）
     *                    diff 差值
     * @return UUIDS和结果信息
     */
    @GetMapping("/read")
    public Map<String, Object> sendReadRequest(
            @RequestParam String devId,
            @RequestParam(defaultValue = "VW") String addressType,
            @RequestParam(defaultValue = "0") int startValue,
            @RequestParam(defaultValue = "5118") int endValue,
            @RequestParam(defaultValue = "4") int increment,
            @RequestParam(required = false) Double targetValue, Double diff) {

        if (targetValue == null) {
            targetValue = 0.0;
        }

        List<String> uuids = plcDataService.sendReadRequest(devId, addressType, startValue, endValue, increment, targetValue, diff);
        return Map.of(
                "success", true,
                "message", "Read request sent successfully. Subscribed to HMI/11005/" + devId + "/read/",
                "datas", uuids
        );
    }

    /**
     * 读取开关地址（主地址0~31，子地址0~7）
     *
     * @param devId 设备ID
     * @return UUID列表和结果信息
     * 开关读取：GET http://localhost:8080/api/plc/read/switch?devId=1100504
     */
    @GetMapping("/read/switch")
    public Map<String, Object> sendSwitchReadRequest(@RequestParam String devId,@RequestParam(defaultValue = "M") String addressType) {
        List<String> uuids = plcDataService.sendSwitchReadRequest(devId,addressType);
        return Map.of(
                "success", true,
                "message", "Switch read request sent. Subscribed to HMI/11005/" + devId + "/read/",
                "uuids", uuids,
                "uuidCount", uuids.size()
        );
    }

    /**
     * 获取指定UUID的接收数据
     */
    @GetMapping("/data/{uuid}")
    public Map<String, Object> getData(@PathVariable String uuid) {
        Map<String, Number> data = plcDataService.getReceivedData(uuid);

        if (data == null) {
            return Map.of(
                    "success", false,
                    "message", "No data found for UUID: " + uuid
            );
        }

        return Map.of(
                "success", true,
                "uuid", uuid,
                "data", data
        );
    }

    /**
     * 获取所有接收数据
     */
    @GetMapping("/data")
    public Map<String, Object> getAllData() {
        return Map.of(
                "success", true,
                "data", plcDataService.getAllReceivedData()
        );
    }

    /**
     * 在多个设备中轮流下发地址数据
     *
     * @param addressType 地址类型，如 "VD"
     * @param startValue  起始值
     * @param endValue    终止值
     * @param increment   增量
     * @param targetValue 目标值（用于标记接近的值）
     * @param diff        差值
     * @return UUID列表和结果信息
     * # 方式1：通过参数生成地址并轮流下发
     * GET http://localhost:8080/api/plc/read/multiple?addressType=VD&startValue=1484&endValue=1496&increment=4&targetValue=0
     * <p>
     * # 方式2：直接提供地址列表
     * GET http://localhost:8080/api/plc/read/multiple?addresses=VD1484,VD1488,VD1492,VD1496&addressType=VD
     *
     */
    @GetMapping("/read/multiple")
    public Map<String, Object> sendReadRequestToMultipleDevices(
            @RequestParam(defaultValue = "VD") String addressType,
            @RequestParam(required = false) Integer startValue,
            @RequestParam(required = false) Integer endValue,
            @RequestParam(defaultValue = "4") int increment,
            @RequestParam(required = false) Double targetValue,
            @RequestParam(required = false) Double diff,
            @RequestParam(required = false) String addresses) {

        if (targetValue == null) {
            targetValue = 0.0;
        }

        List<String> uuids;

        // 如果提供了地址字符串，直接使用；否则通过参数生成
        if (addresses != null && !addresses.isEmpty()) {
            // 解析地址字符串，格式：VD VD1484,VD1488,VD1492,VD1496 或 VD1484,VD1488,VD1492,VD1496
            List<String> addressList = new ArrayList<>();
            String[] parts = addresses.split(",");
            for (String part : parts) {
                part = part.trim();
                if (part.contains(" ")) {
                    // 格式：VD 1484
                    addressList.add(part);
                } else {
                    // 格式：1484，需要添加地址类型
                    if (addressType != null && !addressType.isEmpty()) {
                        addressList.add(addressType + " " + part);
                    } else {
                        addressList.add(part);
                    }
                }
            }
            uuids = plcDataService.sendReadRequestToMultipleDevices(addressList, targetValue, diff);
        } else if (startValue != null && endValue != null) {
            uuids = plcDataService.sendReadRequestToMultipleDevices(
                    addressType, startValue, endValue, increment, targetValue, diff);
        } else {
            return Map.of(
                    "success", false,
                    "message", "Please provide either 'addresses' parameter or 'startValue' and 'endValue' parameters"
            );
        }

        return Map.of(
                "success", true,
                "message", "Read requests sent to multiple devices successfully",
                "deviceCount", 15, // 1100504, 1100506~1100518, 1100588
                "uuids", uuids,
                "uuidCount", uuids.size()
        );
    }
}

